package com.jyxd.web.mq;

import cn.hutool.core.date.DateUtil;
import com.jyxd.web.data.dto.NursingTaskDTO;
import com.jyxd.web.service.assessment.basic.NurseRecordFormService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class NursingTaskExecuteReceiver {

    @Value("${icu.job.mq.nurse.normal.queue}")
    private String nursingTaskExecuteQueue;
    private final Logger logger = LoggerFactory.getLogger(NursingTaskExecuteReceiver.class);

    private final NurseRecordFormService nurseRecordFormService;

    public NursingTaskExecuteReceiver(NurseRecordFormService nurseRecordFormService) {
        this.nurseRecordFormService = nurseRecordFormService;
    }

    @RabbitListener(queuesToDeclare = @Queue("#{nursingTaskExecuteQueue}"))
    public void process(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, @Payload NursingTaskDTO nursingTaskDTO) throws IOException {
        logger.info("当前插入时间:{},护理记录时间:{}", DateUtil.formatDateTime(new Date()), DateUtil.formatDateTime(nursingTaskDTO.getDataTime()));
        logger.info("NursingTaskDTO({}):{}", nursingTaskDTO.hashCode(), nursingTaskDTO);
        //插入数据库
        try{
            nurseRecordFormService.saveAutoGeneratedData(nursingTaskDTO);
        }catch (Exception e){
            logger.error(e.getMessage());
        }finally {
            channel.basicAck(tag, false);
        }
    }

    @Bean(name = "nursingTaskExecuteQueue")
    public String getNursingTaskExecuteQueue() {
        return nursingTaskExecuteQueue;
    }
}
